<template>
  <div class="app-container customer-div">
    <el-dialog
      :close-on-click-modal="false"
      :beforeClose="handleClose"
      title="物流发货"
      :visible.sync="dialogVisible"
      width="700px">
        <el-form label-width="100px" ref="sendForm" :model="sendForm" size="small" :rules="rules">
            <div id="container" style="height:0"></div>
            <el-form-item label="装卸类型">一装一卸</el-form-item>
            <el-form-item label="装货地址" prop="startAddress">
                <el-input style="width:300px" v-model="sendForm.startAddress" disabled></el-input>
                <i class="el-icon-location-outline"  style="font-size:16px;cursor: pointer;display: inline-block;vertical-align: middle" @click="showMap('start',sendForm.startAreaName,sendForm.startAddress)"></i>
                <span style="color:red">必须在地图上选择地点</span>
            </el-form-item>
            <el-form-item label="装货经纬度" prop="startLon">
              <el-input style="width:300px" :value="sendForm.startLon | fiflon(sendForm.startLat)" disabled></el-input>
            </el-form-item>
            <el-form-item label="卸货地址" prop="endAddress">
              <el-input  style="width:300px" v-model="sendForm.endAddress" disabled></el-input>
              <i class="el-icon-location-outline"  style="font-size:16px;cursor: pointer;display: inline-block;vertical-align: middle" @click="showMap('end',sendForm.endAreaName,sendForm.endAddress)"></i>
              <span style="color:red">必须在地图上选择地点</span>
            </el-form-item>
            <el-form-item label="卸货经纬度" prop="endLon">
              <el-input style="width:300px" :value="sendForm.endLon | fiflon(sendForm.endLat)" disabled></el-input>
              <span style="padding-left:5px;">预计距离：<span style="font-weight: bold;color:Red">{{ distance }}</span> 公里</span>
            </el-form-item>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="货物信息" prop="cargoName">
                <el-input style="width:150px" v-model="sendForm.cargoName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="包装" >
                <el-select  style="width:100px" v-model="sendForm.packingTypeTags">
                  <el-option :value="item.id" :label="item.name" v-for="(item,index) in bzList" :key="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="重量" label-width="60px" prop="inquiryNum">
                <el-input v-model="sendForm.inquiryNum" style="width:100px" @change="changeInquiryNum"></el-input> <span style="padding-left:10px">吨</span>
              </el-form-item>
            </el-col>
          </el-row>
            <el-form-item label="车型车长" prop="truckLengthList">
                <el-input :disabled="true" :value="sendForm.lclCargo | fiftext(sendForm.truckLengthList,sendForm.truckTypeList,truckTypeList,lclCargoList)" style="width:300px;"></el-input>
                <el-button type="text" style="margin-left:10px" @click="showPop3">选择车型车长</el-button>
                <el-input type="hidden" :value="sendForm.truckLengthList | fifArrayToText" style="height:0;display: none"/>
            </el-form-item>
             <el-form-item label="装车时间" prop="loadTime">
               <el-date-picker
                 @change="countFreight"
                 value-format="yyyy-MM-dd HH:mm"
                 v-model="sendForm.loadTime"
                 type="datetime"
                 placeholder="选择日期时间">
               </el-date-picker>
               <span style="padding-left:10px;font-size:12px;color:#999;">注：装车时间最小为 <span style="color:red">当前时间往后推两小时</span></span>
             </el-form-item>
              <el-form-item label="卸车时间" prop="unloadTime">
                <el-date-picker
                  value-format="yyyy-MM-dd HH:mm"
                  v-model="sendForm.unloadTime"
                  type="datetime"
                  placeholder="选择日期时间">
                </el-date-picker>
                <span style="padding-left:10px;font-size:12px;color:#999;">注：卸车时间不能早于装车时间</span>
              </el-form-item>
            <el-form-item label="备注">
                <el-input  type="textarea" :rows="2" placeholder="请输入内容" v-model="sendForm.description"></el-input>
            </el-form-item>
            <el-form-item label="特殊需求">
              <el-select v-model="sendForm.tsxq" multiple placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in tsxqList"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="支付方式">
                <el-select v-model="sendForm.payMethodByEnum">
                   <el-option :value="item.id" :label="item.name" v-for="(item,index) in zfList" :key="index"></el-option>
                </el-select>
              <el-radio-group v-model="sendForm.invoiceType" style="margin-left:55px">
                <el-radio :label="1" border>开发票</el-radio>
                <el-radio :label="-1" border>不开发票</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="成交模式">
              <el-radio-group v-model="sendForm.dealModelStr">
                <el-radio label="auction" border>智能议价</el-radio>
                <el-radio label="buyout" border>一口价</el-radio>
                <el-radio label="tel" border>电话议价</el-radio>

              </el-radio-group>
            </el-form-item>
          <el-form-item label="运费" prop="charges">
            <el-input v-model="sendForm.charges" style="width:150px"></el-input> <span style="padding-left:10px">元/{{ sendForm.freightUnit == 1 ? '趟' : '吨'}}</span>
            <el-radio-group v-model="sendForm.freightUnit" style="margin-left:55px" @change="countFreight">
              <el-radio :label="1" border>趟</el-radio>
              <el-radio :label="2" border>吨</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="建议运费">
            <span style="color:red;font-weight: bold">{{charges2}}<span style="padding-left:10px">元/{{ sendForm.freightUnit == 1 ? '趟' : '吨'}}</span></span>
          </el-form-item>
          <el-form-item label="订金">
            <el-input v-model="sendForm.deposit" style="width:150px"></el-input>
            <el-radio-group v-model="sendForm.needReturnDeposit" style="margin-left:55px">
              <el-radio :label="1" border>退还</el-radio>
              <el-radio :label="0" border>不退还</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="合计费用">
               <div style="font-size:16px;font-weight: bold;color:red">￥{{ sendForm.charges | fifymmAmount(sendForm.inquiryNum , sendForm.freightUnit) }}</div>
          </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
    <gaodeMap @handleConfirm="handleConfirm2" ref="gaodeMap"></gaodeMap>

    <el-dialog :close-on-click-modal="false"
               title="车型车长"
               :visible.sync="dialogVisible3"
               width="700px">
        <div class="chexing-con">
            <div class="chexing-title">用车类型</div>
            <div class="chexing-item-list">
                <div class="chexing-item" :class="{'choose' : selectlclCargo == item.id}" @click="selectItem('selectlclCargo',item.id,'one')" v-for="(item,index) in lclCargoList" :key="index">
                  {{ item.name }}
                </div>
            </div>
            <div class="chexing-title">车长<span style="font-size:12px;color:#888;font-weight: 400;padding-left:10px">多选，最多三项</span></div>
            <div class="chexing-item-list">
                <div class="chexing-item" :class="{'choose' : selecttruckLengthList.indexOf(item) != -1}" @click="selectItem('selecttruckLengthList',item,'more')" v-for="(item,index) in truckLengthList" :key="index">
                  {{ item }}
                </div>
            </div>
            <div class="chexing-title">车型 <span style="font-size:12px;color:#888;font-weight: 400;padding-left:10px">多选，最多三项</span></div>
            <div class="chexing-item-list">
              <div class="chexing-item" :class="{'choose' : selecttruckTypeList.indexOf(item.id) != -1}" @click="selectItem('selecttruckTypeList',item.id,'more')" v-for="(item,index) in truckTypeList" :key="index">
                {{ item.name }}
              </div>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose3">取 消</el-button>
          <el-button type="primary" @click="handleConfirm3" >确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script>
import gaodeMap from '@/views/components/gaodeMap'
import {addSource, checkFreighInquiry, planGoodsInfo} from "../../api/partner";
import axios from 'axios'
const defaultSendForm={
  "startAreaName":"",//装货省市区
  "startAddress":"",//装货地址
  "startLon":"",//装货地址纬度
  "startLat":"",//装货地址经度
  "endAreaName":"",//收货省市区
  "endAddress":"",//收货地址
  "endLon":"",//收货地址纬度
  "endLat":"",//收货地址经度
  "inquiryNum":'',//发货数量
  "cargoName":"塑料原料",//货物信息
  "dpgId":'',//排货记录ID
  "dealModelStr":"auction",//成交模式(tel:电话议价，auction:智能议价，buyout:一号价)
  "deposit":'50',//订金
  "needReturnDeposit":1,//是否退还订金(1是，0否)
  "charges":'',//运费
  "freightUnit":1,//运费单位(1:趟，2吨，3方，4件)
  "truckTypeList":[1,2,3],//车型列表(1:平板 2:高栏,3:厢式,4:集装箱,8自卸,9冷藏,10保温,12高低板,13面包车,14棉被车)
  "truckLengthList":[],//车长
  "invoiceType":1,//开票类型（1：开发票，-1不开票）
  "payMethodByEnum":5,//支付方式
  "description":"",//备注
  "loadTime":"",//装货时间
  "unloadTime":"",//卸货时间
  "packingTypeTags":3,//包装方式(0其他，1纸箱，2筐装，3散装，4托盘，5捆扎，6袋装，7裸装)
  tsxq:[],//特殊需求
  lclCargo:0,
};
export default {
  name: "sendGoods",
  data(){

    return {
      dialogVisible: false,
      btnLoading: false,
      placeSearch: null,
      geocoder:null,
      adrText:'',
      Lng:'',
      Lat:'',
      province:'',
      city:'',
      district:'',
      sendForm:JSON.parse(JSON.stringify(defaultSendForm)),
      bzList:[
        {name:'其他',id:0},
        {name:'纸箱',id:1},
        {name:'筐装',id:2},
        {name:'散装',id:3},
        {name:'托盘',id:4},
        {name:'捆扎',id:5},
        {name:'袋装',id:6},
        {name:'裸装',id:7}
      ],
      zfList:[
        {name:'到付+回单',id:4},
        {name:'全额到付',id:5},
        {name:'全额回单',id:6},
      ],
      blackType:'',
      tsxqList:['三不超','需雨布','有禁区','需回单','需压车','禁止配货','全程高速','随时装','高价急走','绿通'],
      dialogVisible3:false,
      truckLengthList:[1.8,2.7,3.8,4.2,5,6.2,6.8,7.7,8.2,8.7,9.6,11.7,12.5,13,13.7,15,16,17.5],
      truckTypeList:[
        {id:1,name:'平板'},{id:2,name:'高栏'},{id:3,name:'厢式'},{id:4,name:'集装箱'},{id:8,name:'自卸'},
        {id:9,name:'冷藏'},{id:10,name:'保温'},{id:12,name:'高低板'},{id:13,name:'面包车'},{id:14,name:'棉被车'},
      ],
      lclCargoList:[{id:0,name:'整车'},{id:1,name:'零担货源'}],
      selecttruckLengthList:[],
      selecttruckTypeList:[],
      selectlclCargo:'',
      ymmAmount:'',
      rules:{
        startAddress:[{required: true, trigger: 'change' ,message: '此项必填'}],
        endAddress:[{required: true, trigger: 'change' ,message: '此项必填',}],
        startLon:[{required: true, trigger: 'change' ,message: '此项必填'}],
        endLon:[{required: true, trigger: 'change' ,message: '此项必填',}],
        cargoName:[{required: true, trigger: 'change' ,message: '此项必填',}],
        truckLengthList:[{required: true, trigger: 'change' ,message: '请选择车长',}],
        loadTime:[{required: true, trigger: 'change' ,message: '此项必填',}],
        unloadTime:[{required: true, trigger: 'change' ,message: '此项必填',}],
        inquiryNum:[{required: true, trigger: 'blur',message: '此项必填'}],
        charges:[{required: true, trigger: 'blur',message: '此项必填'}],
        geocoder:null
      },
      charges2:'',
      distance:'--'
    }
  },
  components : {
    gaodeMap:gaodeMap
  },
  computed: {

  },
  filters:{
    fiflon(lon,lat){
      return lon + ' ' +lat
    },
    fiftext(lclCargo,truckLengthList,truckTypeList,alltruckTypeList,alllclCargoList){
      let typeText = [];
      let c = -1;
      let d = -1;
      truckTypeList.forEach((el)=>{
        c = alltruckTypeList.findIndex((ee)=>{
            return ee.id == el
         })
        if(c != -1){
          typeText.push(alltruckTypeList[c].name)
        }
      })
      let clCargoText = '';
      d =  alllclCargoList.findIndex((ee)=>{
        return ee.id == lclCargo
      })
      if(d != -1){
        clCargoText = alllclCargoList[d].name;
      }
      return clCargoText+','+ truckLengthList.join(",")+','+typeText.join(",")
    },
    fifArrayToText(val){
      return val.join(",")
    },
    fifymmAmount(price,num,freightUnit){
      if(price && num){
        if(freightUnit == 2){
          return (parseFloat(price) * parseFloat(num)).toFixed(2)
        }else{
          return parseFloat(price).toFixed(2)
        }

      }else{
        return ''
      }
    },

  },
  created() {

  },
  methods:{
    showPop(item){
      this.dialogVisible = true;
      this.geocoder = new AMap.Geocoder();
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
      planGoodsInfo({dpgId:item.dpgId}).then((res)=>{
        this.sendForm.inquiryNum = res.takeNum;
        this.sendForm.dpgId = item.dpgId;
        this.sendForm.loadTime = res.takeTime + ' 12:00';

        this.sendForm.startAddress = res.takeAddress;
        this.sendForm.startAreaName = res.startAreaName;
        this.sendForm.endAddress = res.addressInfo;
        this.sendForm.endAreaName = res.endAreaName;
        this.sendForm.startLon = '';
        this.sendForm.startLat = '';
        this.sendForm.endLon = '';
        this.sendForm.endLat = '';
        this.changeInquiryNum();
        // if(res.takeAddress && res.addressInfo) {
        //   this.getJWD(item.takeAddress).then((startLnglat) => {
        //     this.sendForm.startAddress = res.takeAddress;
        //     this.sendForm.startAreaName = res.startAreaName;
        //     this.sendForm.startLon = startLnglat.lng;
        //     this.sendForm.startLat = startLnglat.lat;
        //     this.changeInquiryNum();
        //   })
        //   this.getJWD(res.addressInfo).then((endLnglat) => {
        //     this.sendForm.endAddress = res.addressInfo;
        //     this.sendForm.endAreaName = res.endAreaName;
        //     this.sendForm.endLon = endLnglat.lng;
        //     this.sendForm.endLat = endLnglat.lat;
        //     this.changeInquiryNum();
        //   })
        // }else{
        //     this.changeInquiryNum();
        //   }
      })
    },
    //计算起点与经点距离
    countDistance(){
      let self = this;
       if(this.sendForm.startLon != '' && this.sendForm.endLon != ''){
         axios.get('https://restapi.amap.com/v3/distance?parameters', {
           params: {
             key: '1b7d62b3008f8328c25201eec2cc6494',
             type:1,
             origins:self.sendForm.startLon+','+self.sendForm.startLat,
             destination:self.sendForm.endLon+','+self.sendForm.endLat,
           }
         })
           .then(function (response) {
             // console.log("response",response)
             if(response.data.info == 'OK'){
               self.distance = response.data.results[0] && response.data.results[0].distance ? (response.data.results[0].distance/1000).toFixed(2) : '--'
             }else{
               self.distance = '--'
             }
             // console.log("distance",self.distance)
           })
           .catch(function (error) {

           });
       }
    },

    //获取经纬度
    getJWD(address){
      return new Promise((resolve ,reject)=>{
        this.geocoder.getLocation(address, (status, result)=> {
          console.log("address",address);
          console.log("result",result)
          if (status === 'complete'&&result.geocodes.length) {
            var lnglat = result.geocodes[0].location
            console.log("lnglat",lnglat);
            resolve(lnglat)
          }else{
            this.$message.error('根据地址查询位置失败');
            reject('1')
          }
        });
      })


    },

    //重量改变时重新计算车型
    changeInquiryNum(){
      if(this.sendForm['inquiryNum'] <= 3)
      {this.sendForm.truckLengthList = [3.8,4.2];}
      else if(this.sendForm['inquiryNum'] <= 5)
      {this.sendForm.truckLengthList = [4.2,5];}
      else if(this.sendForm['inquiryNum'] <= 11)
      { this.sendForm.truckLengthList = [6.2,6.8];}
      else if(this.sendForm['inquiryNum'] <= 20)
      {this.sendForm.truckLengthList = [9.6];}
    else
      {this.sendForm.truckLengthList = [13,13.7];}
      this.countFreight()
    },

    //计算运费
    countFreight(){
      let propsI = 0;
      this.$refs['sendForm'].validateField(['startLon','endLon','inquiryNum','loadTime','truckLengthList'],(errorMessage) => {
          if (!errorMessage) {
            propsI++;
          }
        });
        if (propsI >= 5) {
          let data = {};
          data.startAreaName = this.sendForm.startAreaName;
          data.startAddress = this.sendForm.startAddress;
          data.startLon = this.sendForm.startLon;
          data.startLat = this.sendForm.startLat;
          data.endAreaName = this.sendForm.endAreaName;
          data.endAddress = this.sendForm.endAddress;
          data.endLon = this.sendForm.endLon;
          data.endLat = this.sendForm.endLat;
          data.truckTypeList = this.sendForm.truckTypeList.join(",");
          data.truckLengthList = this.sendForm.truckLengthList.join(",");
          data.lclCargo = this.sendForm.lclCargo;
          data.loadTime = this.sendForm.loadTime;
          data.unloadTime = this.sendForm.unloadTime;
          data.inquiryNum = this.sendForm.inquiryNum;
          data.freightUnit = this.sendForm.freightUnit;
          data.actionType = 'addSource'
          checkFreighInquiry(data).then((res)=>{
            // this.sendForm.charges = data.freightUnit == 1 ? res.ymmAmount : res.ymmPrice;
            this.charges2 = data.freightUnit == 1 ? res.ymmAmount : res.ymmPrice;
            // this.ymmAmount = res.ymmAmount;
            this.$message.success('建议运费计算成功！')
          })
        }

    },

    //显示车型车长
    showPop3(){
      this.dialogVisible3 = true;
      this.selecttruckLengthList = JSON.parse(JSON.stringify(this.sendForm.truckLengthList))
      this.selecttruckTypeList = JSON.parse(JSON.stringify(this.sendForm.truckTypeList));
      this.selectlclCargo = this.sendForm.lclCargo ;

    },

    //关闭车型车长
    handleClose3(){
      this.dialogVisible3 = false;
    },

    //确认车型车长
    handleConfirm3(){
        if(this.selecttruckLengthList.length == 0){
          this.$message.error('请选择车长！')
          return false
        }
        if(this.selecttruckTypeList.length ==0){
          this.$message.error('请选择车型！')
          return false
        }
        this.sendForm.truckLengthList = JSON.parse(JSON.stringify(this.selecttruckLengthList));
        this.sendForm.truckTypeList = JSON.parse(JSON.stringify(this.selecttruckTypeList));
        this.sendForm.lclCargo = this.selectlclCargo;
        this.dialogVisible3 = false;
        this.countFreight();
    },

    //选择项
    selectItem(name,val,type){
      if(type == 'more'){ //多选
        if(this[name].indexOf(val) == -1){
          if(this[name].length > 2){
            this.$message.error('最多选择3项！')
          }else{
            this[name].push(val);
          }

        }else{
          let i=this[name].indexOf(val);
          this[name].splice(i, 1);
        }
      }else{ //单选
        if(this['select'+name] != val){

          this[name] = val;
        }else{
          this[name] = '';
        }
      }
    },

    handleConfirm2(adrInfo){
      console.log("adrInfo",adrInfo)
      this.sendForm[this.blackType+'Address'] = adrInfo.adrText;
      this.sendForm[this.blackType+'AreaName'] = [adrInfo.province,adrInfo.city ? adrInfo.city :adrInfo.province,adrInfo.district].join("_");
      this.sendForm[this.blackType+'Lon']= adrInfo.Lng;
      this.sendForm[this.blackType+'Lat']= adrInfo.Lat;
      this.countFreight();
      // this.countDistance();
    },

    //显示地图
    showMap(type,areaName,addresstext) {
      this.dialogVisible = true;
      this.blackType = type;
      this.$refs.gaodeMap.showMap(areaName,addresstext)
    },

      handleClose(){
        this.dialogVisible = false;
      },

      handleConfirm(){
        if(new Date(this.sendForm.loadTime).getTime() > new Date(this.sendForm.unloadTime).getTime()){  //装货时间大于卸货时间
            this.$message.error('装货时间大于卸货时间！')
            return false
        }
        this.$refs['sendForm'].validate((valid) => {
          if (valid) {
            this.btnLoading = true;
            let data = JSON.parse(JSON.stringify(this.sendForm));
            data.truckTypeList = data.truckTypeList.join(",");
            data.truckLengthList = data.truckLengthList.join(",");
            let tsxq = '';
            if(data.tsxq.length > 0){
              tsxq= ','+data.tsxq.join(",")
            }
            data.description = data.description + tsxq
            addSource(data).then(()=>{
              this.btnLoading = false;
              this.dialogVisible = false;
              this.$message.success('发布成功！')
              this.$emit('handleConfirm',this.sendForm.dpgId)
            }).catch(()=>{
              this.btnLoading = false;
            })
          }
        })
      },
  },
}
</script>

<style scoped lang="scss">
    .chexing-con{
      .chexing-title{
          font-weight: bold;
          font-size:14px;
          margin-bottom:10px;
      }
      .chexing-item-list{
        overflow: hidden;
        .chexing-item{
          display: inline-block;
          width:80px;
          height:30px;
          line-height: 30px;
          background: #eee;
          text-align: center;
          color:#666;
          margin-right:10px;
          margin-bottom:10px;
          cursor: pointer;
        }
        .chexing-item.choose{
          background: #f56c6c;
          color:#fff
        }

      }
    }
</style>
